//
//  SEGVisitorAccessDoorViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/4.
//

#import "SEGVisitorAccessDoorViewModel.h"
#if __has_include(<Commom/SEGCommonDoorManager.h>)
#import <Commom/SEGCommonDoorManager.h>
#else
#import "SEGCommonDoorManager.h"
#endif

@implementation SEGVisitorAccessDoorViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        self.doorArray = [NSMutableArray array];
        self.selectDoorArray = [NSMutableArray array];
        [self seg_createCommand];
    }
    return self;
}
- (void)seg_createCommand {
    @weakify(self);
    self.command = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [[SEGCommonDoorManager sharedManager] requestmyDoorListFinished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    NSArray *doorArray = [result valueForKey:@"data"];
                    for (NSDictionary *dic in doorArray) {
                        NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:dic];
                        [tempDic setObject:@"0" forKey:@"select"];
                        [self.doorArray addObject:tempDic];
                    }
                    [subscriber sendNext:self.doorArray];
                    [subscriber sendCompleted];
                } else {
                    NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            return nil;
        }];
    }];
}

- (void)seg_didSelectedDoorAtIndexPathRow:(NSUInteger)indexPathRow {
    NSDictionary *dict = self.doorArray[indexPathRow];
    if ([dict[@"select"] isEqualToString:@"1"]) {
        [dict setValue:@"0" forKey:@"select"];
        [self.selectDoorArray removeObject:dict];
    } else {
        [dict setValue:@"1" forKey:@"select"];
        [self.selectDoorArray addObject:dict];
    }
}
- (NSDictionary *)seg_getSelectedDoorInfo {
    NSMutableDictionary *doorInfoDict = [NSMutableDictionary dictionary];
    NSMutableArray *doorIdArray = [[NSMutableArray alloc] init];
    NSMutableArray *doorNameArray = [[NSMutableArray alloc] init];
    [self.selectDoorArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [doorIdArray addObject:ValueToString([obj valueForKey:@"doorId"])];
        [doorNameArray addObject:ValueToString([obj valueForKey:@"name"])];
    }];
    [doorInfoDict setObject:[doorIdArray componentsJoinedByString:@","] forKey:@"doorIds"];
    [doorInfoDict setObject:[doorNameArray componentsJoinedByString:@","] forKey:@"doorNames"];
    return doorInfoDict;
}

@end
